package com.cl.websocketboot.timer;

import com.cl.websocketboot.constant.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Calendar;

@Component
@Slf4j
@EnableScheduling
public class CleanMsgTask {

    @Value("${socket.cleanMsgDay}")
    private int cleanMsgDay;

    private final SimpMessagingTemplate simpMessagingTemplate;

    public CleanMsgTask(SimpMessagingTemplate simpMessagingTemplate) {
        this.simpMessagingTemplate = simpMessagingTemplate;
    }

    @Scheduled(cron = "0 0 6 * * ? ")
    public void cleanMsg() {
        log.info("清理过期消息开始");
        Constant.messagesOfRoom.forEach((k, messageList) -> messageList.removeIf(next -> next.getSendDateTime().plusDays(cleanMsgDay).isAfter(LocalDateTime.now())));
        Constant.messagesOfRoom.entrySet().removeIf(stringListEntry -> stringListEntry.getValue().isEmpty());
        Constant.messagesOfRoom.keySet().forEach(roomId -> {
            String messageJson = Constant.systemMessageJson(roomId, "清理超过" + cleanMsgDay + "天的消息");
            simpMessagingTemplate.convertAndSend("/room/" + roomId + "/message", messageJson);
        });
        log.info("清理过期消息结束");
    }

    @Scheduled(cron = "0 0 0/1 * * ? ")
    public void hourlyMsg() {
        log.info("整点报时开始");
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        Constant.messagesOfRoom.keySet().forEach(roomId -> {
            String messageJson = Constant.systemMessageJson(roomId, hour + "点了！");
            simpMessagingTemplate.convertAndSend("/room/" + roomId + "/message", messageJson);
        });
        log.info("整点报时结束");
    }
}
